import { Input, Typography } from 'antd';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

import { PrismCode } from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import xssCode from '@/pages/vulnerable/code/xss';
import { judgeScript } from '@/utils/judgeAttack';
import messageBox from '@/utils/messageBox';

const { Title, Text } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: xssCode.href,
};

const Vulnerable: React.FC = () => {
  const [favoriteWebsite, setFavoriteWebsite] = useState<string>('');
  const { t } = useTranslation();

  const handleKeydown = (e: any) => {
    if (e.key === 'Enter') {
      setFavoriteWebsite(e.target.value);
      if (judgeScript(e.target.value)) {
        messageBox.info({ content: t('xss.insertScript') });
      }
    }
  };

  return (
    <>
      <Title italic level={4}>
        {t('xss.href.title')}
      </Title>
      <Input maxLength={20} onKeyDown={handleKeydown} />
      <Title className="mt-5" italic level={4}>
        {t('xss.href.response')}
      </Title>
      <Text>
        {t('xss.href.favoriteWebsite')}&nbsp;
        {/* 注意React此处插值语法会自动进行html转义 */}
        <a href={favoriteWebsite}>{favoriteWebsite}</a>
      </Text>
    </>
  );
};

const XssHref: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'xss',
    hasCompare: true,
    solutions: 5,
  },
};

export default XssHref;
